package castledefense.gui;

import twl.global.widget.GlobalButton;
import twl.global.widget.SelectedButtonModel;

import castledefense.data.BuildingData;
import castledefense.logic.Selectable;

import de.matthiasmann.twl.Event;
import de.matthiasmann.twl.GUI;

public class BuildingButton extends GlobalButton implements Selectable {

	private BuildingPanel panel;
	private int type;
	
	private boolean hasMoney = true;

	public BuildingButton(String name, int type, BuildingPanel panel) {
		super(name);
		this.panel = panel;
		this.type = type;
		setTooltipContent(getText() + " is used for...");
		setTheme("buildingButtonTheme");
		setSize(43, 43);
		setModel(new SelectedButtonModel());
	}

	public boolean isSelected() {
		return getModel().isSelected();
	}
	
	@Override
	protected void paintBackground(GUI gui){
		calculateResource();
		getAnimationState().setAnimationState(STATE_DISABLED, !hasMoney);
		getAnimationState().setAnimationState(STATE_ARMED, getModel().isArmed());
		getAnimationState().setAnimationState(STATE_HOVER, getModel().isHover());
		getAnimationState().setAnimationState(STATE_SELECTED, getModel().isSelected());
		super.paintBackground(gui);
	}

	public void setSelected(boolean value) {
		UpgradePanel upgradePanel = panel.getStateGUI().getUpgradePanel();

		getModel().setSelected(value);
		if (isSelected()) {
			upgradePanel.setWhichInfo(this);
		} else {
			upgradePanel.nullWhichInfoIfSelected(this);
		}
	}
	
	public String getHotkey(){
		if(type == BuildingData.tower1){
			return "1";
		}else if(type == BuildingData.tower2){
			return "2";
		}else if(type == BuildingData.destroy){
			return "0";
		}
		return "";
	}

	private boolean calculateResource() {
		if (BuildingData.getCost(type) <= BuildingData.money) {
			hasMoney=true;
			return true;
		} else {
			hasMoney=false;
			return false;
		}
	}

	// -------------------------- INPUT EVENT HANDLING -------------------------

	@Override
	protected boolean handleEvent(Event evt) {
		boolean result = super.handleEvent(evt);
		if (evt.getType() == Event.Type.MOUSE_BTNUP) {
			if (evt.getMouseButton() == Event.MOUSE_LBUTTON) {
				if (getModel().isHover()) {
					isClicked();
				}
			}
		}
		return result;
	}

	public void isClicked() {
		setSelected(!isSelected());
		if (isSelected()) {
			panel.setSelection(type);
		} else {
			panel.setSelection(BuildingData.noBuilding);
		}
	}

}
